<template>
  <div class="order-management-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :md="8" :sm="24">
            <el-form-item label="订单号">
              <el-input
                  v-model="searchForm.order_no"
                  placeholder="输入订单编号"
                  clearable
              />
            </el-form-item>
          </el-col>

          <el-col :md="8" :sm="24">
            <el-form-item label="状态">
              <el-select
                  v-model="searchForm.status"
                  placeholder="全部状态"
                  clearable
              >
                <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :md="8" :sm="24">
            <el-form-item label="创建人">
              <el-input
                  v-model="searchForm.created_by"
                  placeholder="输入用户ID"
                  clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" class="text-right">
            <el-button type="primary" @click="handleSearch">
              <el-icon>
                <Search/>
              </el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon>
                <Refresh/>
              </el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
          :data="tableData"
          v-loading="loading"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column prop="created_at" label="申请时间" width="150" align="center"/>
        <el-table-column prop="order_no" label="订单编号" width="230" align="center"/>

        <!-- 新增商品信息列 -->
        <el-table-column label="申请商品" width="550" align="center">
          <template #default="{ row }">
            <div class="product-list">
              <div
                  v-for="(item, index) in row.items"
                  :key="index"
                  class="product-item"
              >
                <el-tag type="info" size="small">{{ item.productId }}</el-tag>
                <span class="quantity">x{{ item.quantity }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="statusTagMap[row.status]">
              {{ statusTextMap[row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_by" label="申请人" width="80" align="center"/>
        <el-table-column prop="operator_id" label="审核人" width="80" align="center"/>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
                v-if="row.status === 'pending'"
                type="success"
                size="small"
                @click="handleApprove(row)"
            >
              通过
            </el-button>
            <el-button
                v-if="row.status === 'pending'"
                type="danger"
                size="small"
                @click="handleReject(row)"
            >
              拒绝
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {Search, Refresh} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {approveOrder, getAllOrdersInfo, refusedOrder} from "@/api/auth.js";

// ================== 模拟数据生成器 ==================
const generateMockData = (count = 200) => {
  const data = []
  const statusList = ['pending', 'approved', 'rejected']
  const userIds = Array.from({length: 50}, (_, i) => 1000 + i)

  // 生成商品信息
  const generateItems = () => {
    const itemCount = Math.floor(Math.random() * 5) + 1 // 1-5个商品
    const items = []
    const usedProducts = new Set()

    for (let i = 0; i < itemCount; i++) {
      let productId
      do {
        productId = Math.floor(Math.random() * 500) + 1 // 商品ID 1-500
      } while (usedProducts.has(productId))

      usedProducts.add(productId)
      items.push({
        productId,
        quantity: Math.floor(Math.random() * 10) + 1 // 数量 1-10
      })
    }
    return items
  }

  for (let i = 1; i <= count; i++) {
    const createdTime = Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
    const status = statusList[Math.floor(Math.random() * 3)]

    data.push({
      id: i,
      order_no: `ORD-${createdTime}-${Math.random().toString(36).slice(2, 6).toUpperCase()}`,
      status: status,
      created_by: userIds[Math.floor(Math.random() * userIds.length)],
      operator_id: status === 'pending' ? null : userIds[Math.floor(Math.random() * userIds.length)],
      created_at: createdTime,
      updated_at: status === 'pending' ? createdTime : createdTime + Math.random() * 24 * 60 * 60 * 1000,
      items: generateItems() // 包含商品信息
    })
  }
  return data
}

// ================== 组件逻辑 ==================
const statusOptions = [
  {value: 'pending', label: '待审核'},
  {value: 'approved', label: '已通过'},
  {value: 'rejected', label: '已拒绝'}
]

const statusTextMap = {
  pending: '待审核',
  approved: '已通过',
  rejected: '已拒绝'
}

const statusTagMap = {
  pending: 'warning',
  approved: 'success',
  rejected: 'danger'
}

// 初始化模拟数据
const mockData = ref([
  {
    id: 1,
    order_no: `ORD-111`,
    status: 'pending',
    created_by: '小明',
    operator_id: '小明',
    created_at: '2022-01-01',
    updated_at: '2022-01-01',
    items: [
      {productId: 1, quantity: 2}
    ] // 包含商品信息
  }
])
const initData = async () => {
  try {
    const res = await getAllOrdersInfo()
    if (res.code === 200) {
      mockData.value = res.data
    } else {
      ElMessage.error(res.mesage)
    }
  } catch (e) {
    ElMessage.error(e)
  }


}
onMounted(() => {
  initData()
})

// 响应式状态
const searchForm = reactive({
  order_no: '',
  status: '',
  created_by: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const tableData = ref([])
const loading = ref(false)

// 过滤后的数据
const filteredData = computed(() => {
  return mockData.value.filter(item => {
    const matchOrderNo = searchForm.order_no
        ? item.order_no.toLowerCase().includes(searchForm.order_no.toLowerCase())
        : true

    const matchStatus = searchForm.status
        ? item.status === searchForm.status
        : true

    const matchCreator = searchForm.created_by
        ? item.created_by.toString() === searchForm.created_by
        : true

    return matchOrderNo && matchStatus && matchCreator
  })
})

// 分页数据计算
const paginationData = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  return filteredData.value.slice(start, start + pagination.size)
})

// 获取订单数据
const fetchOrders = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = paginationData.value
    pagination.total = filteredData.value.length
    loading.value = false
  }, 500)
}

// 审核操作
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定通过该订单吗？', '审核确认', {
      confirmButtonText: '确认通过',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await approveOrder(row.id);
    if (res.code === 200) {
      ElMessage.success('通过成功!')

    } else {
      ElMessage.error(res.message)
    }
    await initData()
    fetchOrders()

  } catch (e) {
    ElMessage.error(e)
  }
}

const handleReject = async (row) => {
  await ElMessageBox.confirm('确定拒绝该订单吗？', '审核确认', {
    confirmButtonText: '确认拒绝',
    cancelButtonText: '取消',
    type: 'warning'
  })
  try {
    const res = await refusedOrder(row.id);
    if (res.code === 200) {
      ElMessage.success('拒绝成功!')
    } else {
      ElMessage.error(res.message)
    }
    await initData();
    fetchOrders();

  } catch (e) {
    ElMessage.error(e)
  }
}

// 分页控制
const handleSizeChange = (newSize) => {
  pagination.size = newSize
  pagination.current = 1
  fetchOrders()
}

const handlePageChange = () => {
  fetchOrders()
}

// 搜索操作
const handleSearch = () => {
  pagination.current = 1
  fetchOrders()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    order_no: '',
    status: '',
    created_by: ''
  })
  handleSearch()
}

// 时间格式化
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const pad = n => n.toString().padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

// 初始化加载
onMounted(fetchOrders)
</script>

<style scoped>
.order-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-right {
  text-align: right;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.product-item {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 4px;
  padding: 4px 8px;
}

.quantity {
  margin-left: 6px;
  color: #606266;
  font-size: 12px;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>